package cc.kigh.framework.handler.url;

import cc.kigh.common.core.domain.MayBeUrl;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.security.web.util.UrlUtils;

import java.io.IOException;

/**
 * @author gylang
 * data 2022/2/25
 */
@JacksonStdImpl
@SuppressWarnings("serial")
public class PrivateUrlSerializer extends StdSerializer<MayBeUrl> {

    private final UrlAuthoritySignService urlAuthoritySignService;


    public PrivateUrlSerializer(UrlAuthoritySignService urlAuthoritySignService) {
        super(MayBeUrl.class);
        this.urlAuthoritySignService = urlAuthoritySignService;
    }


    @Override
    public void serialize(MayBeUrl value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (MayBeUrl.isEmpty(value)) {
            if (UrlUtils.isAbsoluteUrl(value.getValue())) {
                gen.writeString(urlAuthoritySignService.authoritySign(value.getValue()));
            } else {
                gen.writeString(value.getValue());
            }
        }
    }


}
